// pages/organization/newindex.js
import Honey from '../../utils/honey';
let WxParse = require('../../wxParse/wxParse.js');


const app = getApp();
const honey = new Honey();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollflag: '', //顶部导航当前选择
    scrollNum: '', //滚动标签变量，点击滚动到该id位置
    opacity: '', //顶部导航透明度控制
    scrollarr: [], //滚动到各个导航标签距离顶部的距离
    lock: false, //顶部导航点击加锁，防止滚动触发事件
    score: '', //机构评分
    scorewidth: '', //评分宽度,
    storeId: '', //当前机构ID
    store: '', //机构详情信息
    imgArr: [], //机构介绍图片列表
    tag: [],
    openShow: true, //页面加载幕布显示隐藏
    pageNo: 1, //
    pageSize: 5,
    isLoad: true,
    storeId: '', //当前机构ID
    commentList: [], //评价列表
    lookMoreStore: false, //查看更多门店控制参数
    storeList: [], //商家缩略门店列表（仅显示两家）
    scrolltop: '', //当前滚动位置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;

    if (options.check_code && !wx.getStorageSync('user')) {
      wx.setStorageSync('checkCode', options.check_code),
        wx.setStorageSync('pagesUrl', `/pages/organization/newindex?id=${options.id}`),
        wx.switchTab({
          url: '/pages/index/index'
        })
    }
    wx.showLoading({
      title: '加载中...',
    })
    const storeId = options.id;
    const imgReg = /<img.*?(?:>|\/>)/gi;
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    wx.getLocation({
      type: 'gcj02',
      complete: function(res) {
        that.setData({
          longitude: res.longitude ? res.longitude : '',
          latitude: res.latitude ? res.latitude : '',
          user: wx.getStorageSync('user')
        })
        honey.post({
          alias: 'storeInfo',
          data: {
            store_id: storeId,
            lat: res.latitude,
            lng: res.longitude
          },
          success: function(res) {
            let store = res.data.data;
            let score = (res.data.data.score * 1).toFixed(1);
            // store.content = store.content.replace('<br />', '').replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0 auto;" ');
            WxParse.wxParse('article', 'html', store.content, that, 17);

            
            let storeList = store.shop_list.slice(0, 2)
            var arr = store.content.match(imgReg);
            var imgArr = [];
            for (var i = 0; i < arr.length; i++) {
              var src = arr[i].match(srcReg);
              //获取图片地址
              if (src[1]) {
                imgArr.push(src[1]);
              }
            }
            that.setData({
              storeList,
              tag: store.tag ? store.tag.split('|') : [],
              storeId,
              store,
              imgArr: imgArr,
              scorewidth: 83 / 5 * score,
              score
            })
            that.getCommentList();

            //套餐，评价，介绍，推荐距离顶部位置数组


            setTimeout(() => {
              wx.hideLoading();
              that.setData({
                openShow: false
              })
            }, 500)
          }
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const that = this;



  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    const that = this;
    return {
      title: `平台烧钱啦～点击领取大红包！`,
      path: `/pages/organization/newindex?id=${that.data.storeId}&check_code=${that.data.user.check_code}`
    }
  },

  //顶部导航点击切换事件
  updateNum: function(e) {
    const that = this;
    that.setData({
      scrollNum: e.currentTarget.dataset.id,
      scrollflag: e.currentTarget.dataset.id,
      lock: true,
    })
  },

  //滚动事件
  scrollView: function(e) {
    const that = this;
    let scrolltop = e.detail.scrollTop;
    let scrollopacity = e.detail.scrollTop / 280;
    that.setData({
      opacity: scrollopacity,
    })
    for (let i = 0; i < that.data.scrollarr.length; i++) {
      if (scrolltop < that.data.scrollarr[i] && !that.data.lock) {
        that.setData({
          scrollflag: 'scroll' + i
        })
        break;
      }
    }
    that.setData({
      lock: false,
      scrolltop
    })
  },

  //点击机构介绍图片大图展示
  prevImage: function() {
    const that = this;
    wx.previewImage({
      current: that.data.imgArr[0], // 当前显示图片的http链接
      urls: that.data.imgArr // 需要预览的图片http链接列表
    })
  },

  //分店导航按钮
  toNavigation: function(e) {
    const that = this;
    const latitude = e.currentTarget.dataset.lat * 1;
    const longitude = e.currentTarget.dataset.lng * 1;
    const name = e.currentTarget.dataset.name;
    wx.openLocation({
      latitude,
      longitude,
      name,
    })
  },

  //分店电话按钮
  callPhone: function(e) {
    const that = this;
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  //获取机构评价列表数据
  getCommentList: function() {
    const that = this;
    if (that.data.isLoad) {
      that.setData({
        isLoad: false
      })
      honey.post({
        alias: 'commentList',
        data: {
          page: that.data.pageNo,
          page_size: that.data.pageSize,
          store_id: that.data.storeId
        },
        success: function(res) {
          that.setData({
            commentList: honey.mergeArray(that.data.commentList, res.data.data.comment_list),
            pageNo: that.data.pageNo + 1,
            isLoad: (res.data.data.comment_list.length < that.data.pageSize ? false : true)
          })
          let scrollarr = [];
          for (let i = 1; i <= 4; i++) {
            wx.createSelectorQuery().select('#scroll' + i).fields({
              rect: true,
            }, function(res) {
              scrollarr.push(res.top);
              if (i == 3) {
                that.setData({
                  scrollarr
                })
              }
            }).exec()
          }
        }
      })
    }
  },

  //点击打开图片
  previewImage: function(e) {
    const that = this;
    const image = e.currentTarget.dataset.image;
    console.log(image);
    const index = e.currentTarget.dataset.index;
    console.log(index);
    wx.previewImage({
      current: image, // 当前显示图片的http链接
      urls: that.data.commentList[index].smeta.image // 需要预览的图片http链接列表
    })
  },

  //点击查看更多门店
  showMoreStore: function() {
    const that = this;
    if (that.data.lookMoreStore) {
      that.setData({
        lookMoreStore: false
      })
    } else {
      that.setData({
        lookMoreStore: true
      })
    }
    let scrollarr = [];
    for (let i = 1; i <= 4; i++) {

      wx.createSelectorQuery().select('#scroll' + i).boundingClientRect(function(rect) {
        scrollarr.push(rect.top * 1 + that.data.scrolltop * 1);
        if (i == 3) {
          that.setData({
            scrollarr
          })
        }
      }).exec()
    }
  }
})